#include "sdlqtrgb.h"
#include <SDL.h>
#include <QMessageBox>
#include <fstream>
#include <QDir>
#include "xvideo_view.h"
#pragma comment(lib, "SDL2.lib")
static SDL_Window *sdl_win = NULL;
static SDL_Renderer *sdl_render = NULL;
static SDL_Texture *sdl_texture = NULL;
static int sdl_width = 0;
static int sdl_height = 0;
static unsigned char *yuv = NULL;
static int pix_size = 2;
static std::ifstream yuv_file;
static XVideoView *view = NULL;
using namespace std::chrono_literals;
void SdlQtRGB::timerEvent(QTimerEvent *ev)
{
    yuv_file.read((char *)yuv, sdl_width * sdl_height * 1.5);
    if (yuv_file.bad())
    {
        if (!yuv_file.eof())
        {
            QMessageBox::warning(this, "??", "??????");
        }
        exit(0);
    }
    if (view->IsExit())
    {
        view->Close();
        exit(0);
    }
    view->Draw(yuv);
}

SdlQtRGB::SdlQtRGB(QWidget *parent)
    : QWidget(parent)
{
    ui.setupUi(this);
    auto s = qApp->applicationDirPath();
    s += "/400_300_25.yuv";
    s = QDir::toNativeSeparators(s);
    yuv_file.open(s.toStdString(), std::ios::binary);
    if (!yuv_file.is_open())
    {
        QMessageBox::warning(this, "??", "??????");
        return;
    }
    sdl_width = 400;
    sdl_height = 300;
    ui.label->resize(sdl_width, sdl_height);
    view = XVideoView::Create(XVideoView::RenderType::SDL);
    view->Init(sdl_width, sdl_height,
               XVideoView::Format::YUV420P,
               (void *)ui.label->winId());
    yuv = new unsigned char[sdl_width * sdl_height * pix_size];
    memset(yuv, 0, sdl_width * sdl_height * pix_size);
    startTimer(40ms);
}

void SdlQtRGB::resizeEvent(QResizeEvent *ev)
{
    ui.label->resize(size());
    ui.label->move(0, 0);
    auto w = width() * ui.label->devicePixelRatio();
    auto h = height() * ui.label->devicePixelRatio();
    view->Scale(w, h);
}
